package com.example.wan1.app;


import android.database.sqlite.SQLiteDatabase;

import com.example.wan1.dao.MySqliteOpenHelper;
import com.example.wan1.di.DaggerAppComponent;
import com.example.wan1.greenDao.db.DaoMaster;
import com.example.wan1.greenDao.db.DaoSession;
import com.example.wan1.utils.SPUtils;

import androidx.appcompat.app.AppCompatDelegate;
import dagger.android.AndroidInjector;
import dagger.android.support.DaggerApplication;

import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;

/***
 * 创建时间：2020/5/2 15:33
 * 创建人：10850
 * 功能描述：app的入口
 */
public class MyApplication extends DaggerApplication {

    private static volatile MyApplication mInstance;

    public static synchronized MyApplication getInstance() {
        if (mInstance == null) {
            synchronized (MyApplication.class) {
                if (mInstance == null) {
                    mInstance = new MyApplication();
                }
            }
        }
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        initGreenDao();

        initNight();
        //可能是夜间模式放在这，导致Skipped 8 frames!  The application may be doing too much work on its main thread.
    }

    @Override
    protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
        return DaggerAppComponent.builder().create(this);
    }


    /**
     * 初始化GreenDao,直接在Application中进行初始化操作
     */
    private static DaoSession daoSession;

    private void initGreenDao() {
        //数据库名字
        MySqliteOpenHelper mySqliteOpenHelper = new MySqliteOpenHelper(mInstance, "wan.db", null);

        SQLiteDatabase db = mySqliteOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);

        daoSession = daoMaster.newSession();
    }

    /**
     * 提供一个全局的会话
     *
     * @return
     */
    public static DaoSession getDaoSession() {
        return daoSession;
    }

    /***
     * 夜间模式
     */
    private void initNight() {
        int i = (int) SPUtils.get(this, "night_mode_id", 1);
        if (i == MODE_NIGHT_YES) {
            AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
        } else if (i == MODE_NIGHT_NO) {
            AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
        } else if (i == MODE_NIGHT_AUTO_BATTERY) {
            AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
        } else if (i == MODE_NIGHT_FOLLOW_SYSTEM) {
            AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
        }
    }
}
